package com.xiaoyi.intentsdklibrary.SDK.Action;

import android.accessibilityservice.AccessibilityButtonController;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.lmiot.xyclick.Util.LkxLog;
import com.xiaoyi.intentsdklibrary.Bean.ClickAsButtonBean;
import com.xiaoyi.intentsdklibrary.Bean.EditTextBean;
import com.xiaoyi.intentsdklibrary.Bean.PathBean;
import com.xiaoyi.intentsdklibrary.Bean.PointBean;
import com.xiaoyi.intentsdklibrary.Bean.TextBean;
import com.xiaoyi.intentsdklibrary.Bean.TopTipBean;
import com.xiaoyi.intentsdklibrary.Bean.ViewBean;
import com.xiaoyi.intentsdklibrary.ClickViewBean;
import com.xiaoyi.intentsdklibrary.KeyClickBean;
import com.xiaoyi.intentsdklibrary.NoticTextBean;
import com.xiaoyi.intentsdklibrary.PathViewBean;
import com.xiaoyi.intentsdklibrary.SDK.Event.EvenSDK;
import com.xiaoyi.intentsdklibrary.SDK.FloatView.NoteInfoViewSDK;
import com.xiaoyi.intentsdklibrary.SDK.Interface.OnAsKeyListener;
import com.xiaoyi.intentsdklibrary.SDK.SDK;
import com.xiaoyi.intentsdklibrary.ScreenTextBean;
import com.xiaoyi.intentsdklibrary.Utils.StateBarUtil;
import com.youyi.yyviewsdklibrary.Dialog.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.greenrobot.eventbus.EventBus;

public class Accessibility extends AccessibilityService {
    private static final String TAG = "Accessibility";
    private static Accessibility instance;
    private String backKey;
    private String homeKey;
    private List<PointBean> mAllPointList;
    private String mClickText;
    private List<EditTextBean> mEditTextBeanList;
    private NoteInfoViewSDK.FindViewType mFindViewType;
    private AccessibilityNodeInfo mNodeInfoChose;
    private String mNowActivityName;
    private String mNowPackName;
    private boolean mResult;
    private List<TextBean> mTextBeanList;
    private List<ViewBean> mViewBeanList;
    private String recentKey;

    public enum ActionType {
        GLOBAL_ACTION_BACK,
        GLOBAL_ACTION_HOME,
        GLOBAL_ACTION_RECENTS,
        GLOBAL_ACTION_NOTIFICATIONS,
        GLOBAL_ACTION_QUICK_SETTINGS,
        GLOBAL_ACTION_POWER_DIALOG,
        GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN,
        GLOBAL_ACTION_LOCK_SCREEN,
        GLOBAL_ACTION_TAKE_SCREENSHOT
    }

    public static Accessibility getInstance() {
        return instance;
    }

    public void onCreate() {
        super.onCreate();
        backKey = getSystemKey(this, "accessibility_back", "com.android.systemui", "");
        homeKey = getSystemKey(this, "accessibility_home", "com.android.systemui", "");
        recentKey = getSystemKey(this, "accessibility_recent", "com.android.systemui", "");
    }

    public void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        EventBus.getDefault().post(new AsconnectBean(true));
        asButtonMethod();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  // 使用常量替代魔法数字
            AccessibilityButtonController buttonController = getAccessibilityButtonController();
            if (buttonController != null) {  // 添加空值检查
                buttonController.registerAccessibilityButtonCallback(new AccessibilityButtonController.AccessibilityButtonCallback() {
                    @Override  // 添加注解
                    public void onClicked(AccessibilityButtonController controller) {
                        super.onClicked(controller);
                        ToastUtil.success("点击了");
                        EventBus.getDefault().post(new ClickAsButtonBean(true));
                    }

                    @Override
                    public void onAvailabilityChanged(AccessibilityButtonController controller, boolean available) {
                        super.onAvailabilityChanged(controller, available);
                    }
                });
            }
        }
    }

    private static final int FLAGS_WITH_BUTTON = 379;  // 定义常量，提高可读性
    private static final int FLAGS_WITHOUT_BUTTON = 123;
    public void asButtonMethod() {
        try {
            AccessibilityServiceInfo serviceInfo = getServiceInfo();
            if (serviceInfo != null) {  // 添加空值检查
                serviceInfo.flags = ActionAsSDK.getShowAsButton(this)
                        ? FLAGS_WITH_BUTTON
                        : FLAGS_WITHOUT_BUTTON;

                setServiceInfo(serviceInfo);
            }
        } catch (Exception e) {
            Log.e("AccessibilityService", "Failed to update service info", e);  // 添加更好的错误日志
        }
    }
    private ActivityInfo tryGetActivity(ComponentName componentName) {
        try {
            Log.i("younchen", "get appInfo:" + componentName.getPackageName());
            return getPackageManager().getActivityInfo(componentName, 0);
        } catch (PackageManager.NameNotFoundException unused) {
            return null;
        }
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event == null) return;

        switch (event.getEventType()) {
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                //表示一个视图（如按钮、图片、链接等）被点击或触摸
                handleViewClicked(event);
                break;
            case AccessibilityEvent.TYPE_VIEW_LONG_CLICKED:
                //表示某个视图（如按钮、图片、列表项等）被 长按（长时间点击）
                handleViewLongClicked(event);
                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                handleWindowStateChanged(event);
                if (EvenSDK.isListenScreenText) {
                    recycle(getRootInActiveWindow());
                }
                break;
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                //该事件表示通知栏中的通知有变化。它可以帮助无障碍服务监听和响应系统通知的到来、变化、更新等。
                if (EvenSDK.isListenNoticText) {
                    handleNoticText(event);
                }
                break;
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
                //这个事件通常用于监听窗口内容的变化，通常是以下几种情况：
               // 窗口中的视图内容发生了变化（例如，文本框中的文字改变，按钮内容更新）。
               // 窗口发生了布局变更。
                if (EvenSDK.isListenScreenText) {
                    recycle(getRootInActiveWindow());
                }
                break;
        }
    }

    private void handleWindowStateChanged(AccessibilityEvent event) {
        try {
            if (event.getClassName() != null && event.getPackageName() != null) {
                ComponentName componentName = new ComponentName(
                        event.getPackageName().toString(),
                        event.getClassName().toString()
                );
                ActivityInfo activityInfo = tryGetActivity(componentName);
                if (activityInfo != null) {
                    mNowActivityName = activityInfo.name;
                    mNowPackName = activityInfo.packageName;
                }
            }
        } catch (Exception e) {
            Log.e("AccessibilityService", "Error handling window state change", e);
        }
    }

    private void handleViewClicked(AccessibilityEvent event) {
        if (TextUtils.isEmpty(event.getContentDescription())) return;
        String description = event.getContentDescription().toString();
        if (!TextUtils.isEmpty(backKey) && description.equals(backKey)) {
            SDK.mOnAsKeyListener.result(OnAsKeyListener.KeyType.BACK);
        } else if (!TextUtils.isEmpty(homeKey) && description.equals(homeKey)) {
            SDK.mOnAsKeyListener.result(OnAsKeyListener.KeyType.HOME);
        } else if (!TextUtils.isEmpty(recentKey) && description.equals(recentKey)) {
            SDK.mOnAsKeyListener.result(OnAsKeyListener.KeyType.RECNET);
        }
    }

    private void handleViewLongClicked(AccessibilityEvent event) {
        if (TextUtils.isEmpty(event.getContentDescription()) || EvenSDK.onKeyClickListener == null) return;
        String description = event.getContentDescription().toString();
        if (!TextUtils.isEmpty(backKey) && description.equals(backKey)) {
            EvenSDK.onKeyClickListener.onResult(new KeyClickBean(KeyClickBean.KeyClickType.BackLongClick));
        } else if (!TextUtils.isEmpty(homeKey) && description.equals(homeKey)) {
            EvenSDK.onKeyClickListener.onResult(new KeyClickBean(KeyClickBean.KeyClickType.HomeLongClick));
        } else if (!TextUtils.isEmpty(recentKey) && description.equals(recentKey)) {
            EvenSDK.onKeyClickListener.onResult(new KeyClickBean(KeyClickBean.KeyClickType.RecentLongClick));
        }
    }

    public void onInterrupt() {
        EventBus.getDefault().post(new AsconnectBean(false));
    }

    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new AsconnectBean(false));
    }

    public void recycle(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            int childCount = accessibilityNodeInfo.getChildCount();
            // 叶子节点：没有子节点，处理该节点
            if (childCount == 0) {
                CharSequence text = accessibilityNodeInfo.getText();
                if (text != null) {
                    Rect rect = new Rect();
                    accessibilityNodeInfo.getBoundsInScreen(rect);

                    int left = rect.left;
                    int right = rect.right;
                    int top = rect.top;
                    int bottom = rect.bottom;

                    // 发布事件
                    EventBus.getDefault().post(new ScreenTextBean(
                            text.toString(),
                            left, right, top, bottom,
                            left + (right - left) / 2, top + (bottom - top) / 2,
                            accessibilityNodeInfo.getPackageName().toString(),
                            accessibilityNodeInfo.getClassName().toString()
                    ));
                }
            } else {
                // 遍历子节点并递归处理
                for (int i = 0; i < childCount; i++) {
                    try {
                        recycle(accessibilityNodeInfo.getChild(i));
                    } catch (Exception e) {
                        // 只捕获子节点处理中的异常
                        Log.e("AccessibilityNodeInfo", "Error processing child node", e);
                    }
                }
            }
        } catch (Exception e) {
            // 捕获外层异常，输出日志
            Log.e("AccessibilityNodeInfo", "Error processing node", e);
        } finally {
            // 确保回收节点
            accessibilityNodeInfo.recycle();
        }
    }

    @Override
    public boolean onKeyEvent(KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        if (EvenSDK.onKeyClickListener == null) {
            return super.onKeyEvent(keyEvent);
        }

        KeyClickBean keyClickBean = createKeyClickBean(keyEvent, keyCode);
        if (keyClickBean != null) {
            EvenSDK.onKeyClickListener.onResult(keyClickBean);
        }

        return super.onKeyEvent(keyEvent);
    }

    /**
     * 根据系统事件创建事件
     * @param keyEvent
     * @param keyCode
     * @return
     */
    private KeyClickBean createKeyClickBean(KeyEvent keyEvent, int keyCode) {
        int action = keyEvent.getAction();
        KeyClickBean keyClickBean = null;

        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN://音量减小
                keyClickBean = action == 0 ? new KeyClickBean(KeyClickBean.KeyClickType.Volume_Down_Action_Down)
                        : action == 1 ? new KeyClickBean(KeyClickBean.KeyClickType.Volume_Down_Action_Up) : null;
                break;
            case KeyEvent.KEYCODE_VOLUME_UP: //音量增大
                keyClickBean = action == 0 ? new KeyClickBean(KeyClickBean.KeyClickType.Volume_Up_Action_Down)
                        : action == 1 ? new KeyClickBean(KeyClickBean.KeyClickType.Volume_Up_Action_Up) : null;
                break;
            case KeyEvent.KEYCODE_HOME: // Home
                keyClickBean = action == 0 ? new KeyClickBean(KeyClickBean.KeyClickType.Home_Action_Down)
                        : action == 1 ? new KeyClickBean(KeyClickBean.KeyClickType.Home_Action_Up) : null;
                break;
            case KeyEvent.KEYCODE_BACK: // Back
                keyClickBean = action == 0 ? new KeyClickBean(KeyClickBean.KeyClickType.Back_Action_Down)
                        : action == 1 ? new KeyClickBean(KeyClickBean.KeyClickType.Back_Action_Up) : null;
                break;
            case KeyEvent.KEYCODE_APP_SWITCH: //最近应用
                keyClickBean = action == 0 ? new KeyClickBean(KeyClickBean.KeyClickType.Recent_Action_Down)
                        : action == 1 ? new KeyClickBean(KeyClickBean.KeyClickType.Recent_Action_Up) : null;
                break;
            default:
                break;
        }

        return keyClickBean;
    }


    public void handleNoticText(AccessibilityEvent accessibilityEvent) {
        List<CharSequence> text = accessibilityEvent.getText();
        if (!text.isEmpty()) {
            for (CharSequence charSequence : text) {
                if (EvenSDK.mOnNoticTextListener != null) {
                    EvenSDK.mOnNoticTextListener.onResult(new NoticTextBean(accessibilityEvent, charSequence.toString()));
                }
            }
        }
    }

    public static String getSystemKey(Context context, String resourceName, String packageName, String defaultValue) {
        try {
            Resources resourcesForApplication = context.getPackageManager().getResourcesForApplication(packageName);
            int resourceId = resourcesForApplication.getIdentifier(resourceName, "string", packageName);
            if (resourceId != 0) {
                return resourcesForApplication.getString(resourceId);
            } else {
                return defaultValue;
            }
        } catch (Exception e) {
            // 捕获其他可能的异常，返回默认值
            return defaultValue;
        }
    }

    public boolean performAction(ActionType actionType) {
        if (!SDK.isRunning) {
            return false;
        }

        switch (actionType) {
            case GLOBAL_ACTION_BACK:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            case GLOBAL_ACTION_HOME:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
            case GLOBAL_ACTION_RECENTS:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
            case GLOBAL_ACTION_NOTIFICATIONS:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS);
            case GLOBAL_ACTION_QUICK_SETTINGS:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS);
            case GLOBAL_ACTION_POWER_DIALOG:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);
            case GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
            case GLOBAL_ACTION_LOCK_SCREEN:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN);
            case GLOBAL_ACTION_TAKE_SCREENSHOT:
                return performGlobalAction(AccessibilityService.GLOBAL_ACTION_TAKE_SCREENSHOT);
            default:
                return false;
        }
    }

    public boolean clickXY(int x, int y, int duration) {
        // 设置默认点击持续时间
        if (duration <= 0) {
            duration = 50;
        }

        // 如果坐标无效，直接返回 false
        if (x < 0 || y < 0) {
            return false;
        }

        // 发布点击事件
        EventBus.getDefault().post(new ClickViewBean(x, y, 500));
        // 检查运行状态和系统版本要求
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            ToastUtil.err("系统不符合要求");
            return false;
        }

        // 准备循环状态
        setLoopPrepare();
        // 构建手势
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        Path path = new Path();
        path.moveTo(x, y);
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));
        // 执行手势方法
        return gestureMethod(gestureBuilder.build(), new Handler());
    }

    public boolean swipe(int startX, int startY, int endX, int endY, int duration) {
        // 随机偏移处理
        if (ActionAsSDK.getSlipeRandom(this)) {
            startX += getRandomNum(10, 50);
            startY += getRandomNum(10, 50);
            endX += getRandomNum(10, 50);
            endY += getRandomNum(10, 50);
        }

        // 确保参数有效性
        duration = Math.max(duration, 200); // 设置最小持续时间
        startX = Math.max(startX, 0);
        startY = Math.max(startY, 0);
        endX = Math.max(endX, 0);
        endY = Math.max(endY, 0);

        // 检查运行状态和系统版本要求
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            ToastUtil.err("系统不符合要求");
            return false;
        }

        // 预处理
        setLoopPrepare();

        // 创建手势路径
        Path path = new Path();
        path.moveTo(startX, startY);
        path.lineTo(endX, endY);

        // 发布路径事件
        EventBus.getDefault().post(new PathViewBean(path));

        // 构建手势
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));

        // 执行手势
        return gestureMethod(gestureBuilder.build(), new Handler());
    }

    public boolean multiPath(PathBean... pathBeans) {
        // 检查运行状态和系统版本要求
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            ToastUtil.err("系统不符合要求");
            return false;
        }
        // 预处理
        setLoopPrepare();
        // 创建手势构建器
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        for (PathBean pathBean : pathBeans) {
            if (pathBean == null) {
                continue; // 跳过空 PathBean
            }
            // 创建路径
            Path path = new Path();
            path.moveTo(pathBean.getX0(), pathBean.getY0());
            path.lineTo(pathBean.getX1(), pathBean.getY1());

            // 发布路径事件
            EventBus.getDefault().post(new PathViewBean(path));

            // 添加路径到手势
            gestureBuilder.addStroke(
                    new GestureDescription.StrokeDescription(
                            path,
                            0,
                            Math.max(pathBean.getDuration(), 1) // 确保持续时间至少为 1 毫秒
                    )
            );
        }
        // 执行手势
        return gestureMethod(gestureBuilder.build(), new Handler());
    }

    public boolean clickMultiPoint(List<PointBean> list) {
        try {
            if (!SDK.isRunning || Build.VERSION.SDK_INT < 24) {
                return false;
            }
            setLoopPrepare();
            Handler handler = new Handler();
            GestureDescription.Builder builder = new GestureDescription.Builder();
            for (int i = 0; i < list.size(); i++) {
                Path path = new Path();
                path.moveTo((float) list.get(i).getX(), (float) list.get(i).getY());
                builder.addStroke(new GestureDescription.StrokeDescription(path, 0, 50));
            }
            return gestureMethod(builder.build(), handler);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean longClickMultiPoint(int duration, List<PointBean> points) {
        // 检查运行状态和系统版本要求
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.N || points == null || points.isEmpty()) {
            return false;
        }
        // 预处理
        setLoopPrepare();
        // 创建手势构建器
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        // 遍历点集合并添加路径
        for (PointBean point : points) {
            Path path = new Path();
            path.moveTo(point.getX(), point.getY());
            gestureBuilder.addStroke(
                    new GestureDescription.StrokeDescription(
                            path,
                            0,
                            Math.max(duration, 1) // 确保持续时间至少为 1 毫秒
                    )
            );
        }
        // 执行手势
        return gestureMethod(gestureBuilder.build(), new Handler());
    }

    public boolean pathList(int duration, List<PointBean> points) {
        // 检查运行状态、系统版本和输入数据有效性
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.N || points == null || points.isEmpty()) {
            return false;
        }

        try {
            // 预处理
            setLoopPrepare();

            // 创建手势构建器和路径
            GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
            Path path = new Path();

            // 初始化路径起点
            PointBean startPoint = points.get(0);
            float startX = startPoint.getX();
            float startY = startPoint.getY();
            if (ActionAsSDK.getSlipeRandom(this)) {
                startX += getRandomNum(10, 50);
                startY += getRandomNum(10, 50);
            }
            path.moveTo(startX, startY);

            // 构建路径
            for (int i = 1; i < points.size(); i++) {
                PointBean point = points.get(i);
                if (point == null) continue; // 跳过空点

                float x = Math.max(point.getX(), 0); // 确保 X 坐标不小于 0
                float y = Math.max(point.getY(), 0); // 确保 Y 坐标不小于 0

                if (ActionAsSDK.getSlipeRandom(this)) {
                    x += getRandomNum(10, 50);
                    y += getRandomNum(10, 50);
                }

                path.lineTo(x, y);
            }

            // 发布路径事件
            EventBus.getDefault().post(new PathViewBean(path));

            // 构建和执行手势
            gestureBuilder.addStroke(
                    new GestureDescription.StrokeDescription(
                            path,
                            0,
                            Math.max(duration, 1) // 确保持续时间至少为 1 毫秒
                    )
            );
            return gestureMethod(gestureBuilder.build(), new Handler());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public boolean dragTo(PointBean start, PointBean end, int duration) {
        // 检查条件是否满足
        if (!SDK.isRunning || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            ToastUtil.err("条件不符合");
            return false;
        }

        try {
            // 初始化必要参数
            setLoopPrepare();
            Handler handler = new Handler();

            // 定义路径
            Path initialPath = new Path();
            initialPath.moveTo(start.getX(), start.getY());

            Path movePath = new Path();
            movePath.moveTo(start.getX(), start.getY());
            movePath.lineTo(end.getX(), end.getY());

            Path endPath = new Path();
            endPath.moveTo(end.getX(), end.getY());

            // 发布路径可视化事件
            EventBus.getDefault().post(new PathViewBean(movePath));

            // 创建并执行初始手势
            GestureDescription.StrokeDescription initialStroke =
                    new GestureDescription.StrokeDescription(initialPath, 0, 2000, true);
            executeGesture(initialStroke, handler, null);

            // 创建并执行中间手势
            GestureDescription.StrokeDescription continueStroke =
                    initialStroke.continueStroke(movePath, 2000, duration, true);
            executeGesture(continueStroke, handler, null);

            // 创建并执行结束手势
            GestureDescription.StrokeDescription finalStroke =
                    continueStroke.continueStroke(endPath, 2000, 500, false);
            executeGesture(finalStroke, handler, new GestureResultCallback() {
                @Override
                public void onCompleted(GestureDescription gestureDescription) {
                    super.onCompleted(gestureDescription);
                    quitLoop(true);
                }

                @Override
                public void onCancelled(GestureDescription gestureDescription) {
                    super.onCancelled(gestureDescription);
                    quitLoop(false);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable t) {
            // 捕获其他可能的异常
            t.printStackTrace();
        }

        // 阻塞主线程以等待结果
        Looper.loop();
        return mResult;
    }

    /**
     * 执行手势并处理结果回调。
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void executeGesture(GestureDescription.StrokeDescription strokeDescription, Handler handler, GestureResultCallback callback) {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        builder.addStroke(strokeDescription);
        dispatchGesture(builder.build(), callback != null ? callback : new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
            }
        }, handler);
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    private boolean gestureMethod(GestureDescription gestureDescription, Handler handler) {
        try {
            dispatchGesture(gestureDescription, new GestureResultCallback() {

                public void onCompleted(GestureDescription gestureDescription) {
                    LkxLog.d("gestureMethod onCompleted");
                    super.onCompleted(gestureDescription);
                    Accessibility.this.quitLoop(true);
                }

                public void onCancelled(GestureDescription gestureDescription) {
                    LkxLog.d("gestureMethod onCancelled");
                    super.onCancelled(gestureDescription);
                    Accessibility.this.quitLoop(false);
                }
            }, handler);
        } catch (Exception unused) {
            LkxLog.d("gestureMethod 出错了");
            unused.printStackTrace();
        }
        Looper.loop();
        return this.mResult;
    }

    private void setLoopPrepare() {
        this.mResult = false;
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
    }

    private void quitLoop(boolean z) {
        this.mResult = z;
        Looper myLooper = Looper.myLooper();
        if (myLooper != null) {
            myLooper.quit();
        }
    }

    public List<TextBean> findAllText() {
        this.mTextBeanList = new ArrayList();
        recycleText(getRootInActiveWindow());
        return this.mTextBeanList;
    }

    private void recycleText(AccessibilityNodeInfo accessibilityNodeInfo) {
        String charSequence;
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() == 0) {
                    CharSequence text = accessibilityNodeInfo.getText();
                    if (!(text == null || (charSequence = text.toString()) == null)) {
                        Rect rect = new Rect();
                        accessibilityNodeInfo.getBoundsInScreen(rect);
                        int i = rect.left;
                        int i2 = rect.right;
                        int i3 = rect.top;
                        int i4 = rect.bottom;
                        this.mTextBeanList.add(new TextBean(charSequence, i, i2, i3, i4, i + ((i2 - i) / 2), i3 + ((i4 - i3) / 2)));
                        accessibilityNodeInfo.recycle();
                        return;
                    }
                    return;
                }
                for (int i5 = 0; i5 < accessibilityNodeInfo.getChildCount(); i5++) {
                    try {
                        recycleText(accessibilityNodeInfo.getChild(i5));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void clickText(String str, Rect rect, boolean z) {
        this.mClickText = str;
        clickTextMethod(getRootInActiveWindow(), rect, z);
    }

    private void clickTextMethod(AccessibilityNodeInfo accessibilityNodeInfo, Rect rect, boolean z) {
        if (accessibilityNodeInfo != null) {
            for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                try {
                    AccessibilityNodeInfo child = accessibilityNodeInfo.getChild(i);
                    if (child != null) {
                        if (child.getChildCount() == 0) {
                            CharSequence text = child.getText();
                            if (text != null) {
                                String charSequence = text.toString();
                                if (charSequence.equals(this.mClickText) || charSequence.contains(this.mClickText)) {
                                    Rect rect2 = new Rect();
                                    child.getBoundsInScreen(rect2);
                                    int i2 = rect2.left;
                                    int i3 = rect2.right;
                                    int i4 = rect2.top;
                                    int i5 = rect2.bottom;
                                    int width = i2 + (rect2.width() / 2);
                                    int height = i4 + (rect2.height() / 2);
                                    int i6 = 2000;
                                    if (rect == null) {
                                        if (!z) {
                                            i6 = 50;
                                        }
                                        clickXY(width, height, i6);
                                        accessibilityNodeInfo.recycle();
                                        return;
                                    } else if (width < rect.left || width > rect.right || height < rect.top || height > rect.bottom) {
                                        EventBus.getDefault().post(new TopTipBean("文字在区域外！"));
                                        accessibilityNodeInfo.recycle();
                                        return;
                                    } else {
                                        if (!z) {
                                            i6 = 50;
                                        }
                                        clickXY(width, height, i6);
                                        EventBus.getDefault().post(new TopTipBean("发现目标文字！"));
                                        child.recycle();
                                        accessibilityNodeInfo.recycle();
                                        return;
                                    }
                                }
                            } else {
                                child.recycle();
                            }
                        } else {
                            clickTextMethod(child, rect, z);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    private void findClickableParent(AccessibilityNodeInfo accessibilityNodeInfo, Rect rect) {
        if (accessibilityNodeInfo != null) {
            try {
                AccessibilityNodeInfo parent = accessibilityNodeInfo.getParent();
                if (parent == null) {
                    return;
                }
                if (!parent.isClickable()) {
                    findClickableParent(parent, rect);
                } else if (rect == null) {
                    parent.performAction(16);
                } else {
                    Rect rect2 = new Rect();
                    parent.getBoundsInScreen(rect2);
                    int i = rect2.left;
                    int i2 = rect2.right;
                    int i3 = rect2.top;
                    int i4 = rect2.bottom;
                    if (i >= rect.left && i2 <= rect.right && i3 >= rect.top && i4 <= rect.bottom) {
                        parent.performAction(16);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public List<EditTextBean> findAllEditText() {
        this.mEditTextBeanList = new ArrayList();
        recycleEditText(getRootInActiveWindow());
        return this.mEditTextBeanList;
    }

    private void recycleEditText(AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                accessibilityNodeInfo.refresh();
                if (accessibilityNodeInfo.getChildCount() != 0) {
                    for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                        try {
                            recycleEditText(accessibilityNodeInfo.getChild(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (accessibilityNodeInfo.isEditable()) {
                    Rect rect = new Rect();
                    accessibilityNodeInfo.getBoundsInScreen(rect);
                    this.mEditTextBeanList.add(new EditTextBean(accessibilityNodeInfo, rect.left, rect.right, rect.top, rect.bottom));
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void inputTextByPosition(int i, String str) {
        if (i >= 1) {
            List<EditTextBean> findAllEditText = findAllEditText();
            if (findAllEditText.size() > 0) {
                AccessibilityNodeInfo accessibilityNodeInfo = findAllEditText.get(i - 1).getAccessibilityNodeInfo();
                Bundle bundle = new Bundle();
                bundle.putCharSequence(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, str);
                accessibilityNodeInfo.performAction(2097152, bundle);
                accessibilityNodeInfo.recycle();
            }
        }
    }

    public void inputTextByXY(int i, int i2, String str) {
        List<EditTextBean> findAllEditText = findAllEditText();
        if (findAllEditText.size() > 0) {
            for (EditTextBean editTextBean : findAllEditText) {
                AccessibilityNodeInfo accessibilityNodeInfo = editTextBean.getAccessibilityNodeInfo();
                Rect rect = new Rect();
                accessibilityNodeInfo.getBoundsInScreen(rect);
                int i3 = rect.left;
                int i4 = rect.right;
                int i5 = rect.top;
                int i6 = rect.bottom;
                if (i < i3 || i > i4 || i2 < i5 || i2 > i6) {
                    accessibilityNodeInfo.recycle();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putCharSequence(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, str);
                    accessibilityNodeInfo.performAction(2097152, bundle);
                    accessibilityNodeInfo.recycle();
                }
            }
        }
    }

    public void inputTextByRect(Rect rect, String str) {
        List<EditTextBean> findAllEditText = findAllEditText();
        if (findAllEditText.size() > 0) {
            for (EditTextBean editTextBean : findAllEditText) {
                AccessibilityNodeInfo accessibilityNodeInfo = editTextBean.getAccessibilityNodeInfo();
                Rect rect2 = new Rect();
                accessibilityNodeInfo.getBoundsInScreen(rect2);
                int i = rect2.left;
                int i2 = rect2.right;
                int i3 = rect2.top;
                int i4 = rect2.bottom;
                if (rect.left < i || rect.right > i2 || rect.top < i3 || rect.bottom > i4) {
                    accessibilityNodeInfo.recycle();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putCharSequence(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, str);
                    accessibilityNodeInfo.performAction(2097152, bundle);
                    accessibilityNodeInfo.recycle();
                }
            }
        }
    }

    public void inputTextByForm(List<String> list) {
        try {
            List<EditTextBean> findAllEditText = findAllEditText();
            if (findAllEditText.size() > 0) {
                for (int i = 0; i < findAllEditText.size(); i++) {
                    AccessibilityNodeInfo accessibilityNodeInfo = findAllEditText.get(i).getAccessibilityNodeInfo();
                    if (list.size() > i) {
                        Bundle bundle = new Bundle();
                        bundle.putCharSequence(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, list.get(i));
                        accessibilityNodeInfo.performAction(2097152, bundle);
                        accessibilityNodeInfo.recycle();
                    } else {
                        accessibilityNodeInfo.recycle();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getRandomNum(int i, int i2) {
        return (new Random().nextInt(i2) % ((i2 - i) + 1)) + i;
    }

    public List<ViewBean> getAllNode(NoteInfoViewSDK.FindViewType findViewType) {
        this.mFindViewType = findViewType;
        this.mViewBeanList = new ArrayList();
        recycleAllByType(getRootInActiveWindow());
        return this.mViewBeanList;
    }

    private void recycleAllByType(AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() != 0) {
                    if (accessibilityNodeInfo.isVisibleToUser()) {
                        addViewBeanByType(false, accessibilityNodeInfo);
                    }
                    for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                        try {
                            recycleAllByType(accessibilityNodeInfo.getChild(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (accessibilityNodeInfo.isVisibleToUser()) {
                    addViewBeanByType(true, accessibilityNodeInfo);
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    private void addViewBeanByType(boolean z, AccessibilityNodeInfo accessibilityNodeInfo) {
        ViewBean viewBean;
        String str = "";
        String charSequence = accessibilityNodeInfo.getClassName() != null ? accessibilityNodeInfo.getClassName().toString() : str;
        String viewIdResourceName = accessibilityNodeInfo.getViewIdResourceName() != null ? accessibilityNodeInfo.getViewIdResourceName() : str;
        String charSequence2 = accessibilityNodeInfo.getText() != null ? accessibilityNodeInfo.getText().toString() : str;
        if (accessibilityNodeInfo.getContentDescription() != null) {
            str = accessibilityNodeInfo.getContentDescription().toString();
        }
        Rect rect = new Rect();
        accessibilityNodeInfo.getBoundsInScreen(rect);
        int i = rect.left;
        int i2 = rect.right;
        int i3 = rect.top;
        int i4 = i + ((i2 - i) / 2);
        int i5 = i3 + ((rect.bottom - i3) / 2);
        rect.offset(0, StateBarUtil.getStatusBarHeight(this) * -1);
        if (Build.VERSION.SDK_INT >= 24) {
            viewBean = new ViewBean(this.mNowPackName, this.mNowActivityName, charSequence, accessibilityNodeInfo.getViewIdResourceName(), rect, charSequence2, str, accessibilityNodeInfo.getDrawingOrder(), i4, i5, z, accessibilityNodeInfo.isClickable(), accessibilityNodeInfo.isLongClickable(), accessibilityNodeInfo.isCheckable(), accessibilityNodeInfo.isEditable(), accessibilityNodeInfo.isScrollable());
        } else {
            viewBean = new ViewBean(this.mNowPackName, this.mNowActivityName, charSequence, viewIdResourceName, rect, charSequence2, str, 0, i4, i5, z, accessibilityNodeInfo.isClickable(), accessibilityNodeInfo.isLongClickable(), accessibilityNodeInfo.isCheckable(), accessibilityNodeInfo.isEditable(), accessibilityNodeInfo.isScrollable());
        }
        switch (mFindViewType.ordinal()) {
            case 1:
                if (accessibilityNodeInfo.isCheckable()) {
                    viewBean.setCheckState(accessibilityNodeInfo.isChecked());
                }
                this.mViewBeanList.add(viewBean);
                return;
            case 2:
                if (accessibilityNodeInfo.isClickable()) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 3:
                if (accessibilityNodeInfo.isLongClickable()) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 4:
                if (accessibilityNodeInfo.isEditable()) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 5:
                if (accessibilityNodeInfo.isCheckable()) {
                    viewBean.setCheckState(accessibilityNodeInfo.isChecked());
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 6:
            case 7:
                if (!TextUtils.isEmpty(accessibilityNodeInfo.getViewIdResourceName())) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 8:
            case 9:
                if (!(accessibilityNodeInfo.getText() == null || TextUtils.isEmpty(accessibilityNodeInfo.getText().toString()))) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 10:
                if (!(accessibilityNodeInfo.getContentDescription() == null || TextUtils.isEmpty(accessibilityNodeInfo.getContentDescription().toString()))) {
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 11:
                if (accessibilityNodeInfo.isCheckable()) {
                    viewBean.setCheckState(accessibilityNodeInfo.isChecked());
                    this.mViewBeanList.add(viewBean);
                    return;
                }
                return;
            case 12:
                if (accessibilityNodeInfo.getClassName().equals("android.widget.ListView") || accessibilityNodeInfo.getClassName().equals("android.support.v7.widget.RecyclerView")) {
                    this.mViewBeanList.add(viewBean);
                    int childCount = accessibilityNodeInfo.getChildCount();
                    if (childCount > 0) {
                        for (int i6 = 0; i6 < childCount; i6++) {
                            AccessibilityNodeInfo child = accessibilityNodeInfo.getChild(i6);
                            addAllView(true, false, child);
                            int childCount2 = child.getChildCount();
                            if (childCount2 > 0) {
                                for (int i7 = 0; i7 < childCount2; i7++) {
                                    recycleAll(true, child);
                                }
                            }
                        }
                        return;
                    }
                    return;
                }
                return;
            default:
                return;
        }
    }

    private void recycleAll(boolean z, AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() != 0) {
                    if (accessibilityNodeInfo.isVisibleToUser()) {
                        addAllView(z, false, accessibilityNodeInfo);
                    }
                    for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                        try {
                            recycleAll(z, accessibilityNodeInfo.getChild(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (accessibilityNodeInfo.isVisibleToUser()) {
                    addAllView(z, true, accessibilityNodeInfo);
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    private void addAllView(boolean z, boolean z2, AccessibilityNodeInfo accessibilityNodeInfo) {
        ViewBean viewBean;
        String str = "";
        String charSequence = accessibilityNodeInfo.getClassName() != null ? accessibilityNodeInfo.getClassName().toString() : str;
        String viewIdResourceName = accessibilityNodeInfo.getViewIdResourceName() != null ? accessibilityNodeInfo.getViewIdResourceName() : str;
        String charSequence2 = accessibilityNodeInfo.getText() != null ? accessibilityNodeInfo.getText().toString() : str;
        if (accessibilityNodeInfo.getContentDescription() != null) {
            str = accessibilityNodeInfo.getContentDescription().toString();
        }
        Rect rect = new Rect();
        accessibilityNodeInfo.getBoundsInScreen(rect);
        int i = rect.left;
        int i2 = rect.right;
        int i3 = rect.top;
        int i4 = i + ((i2 - i) / 2);
        int i5 = i3 + ((rect.bottom - i3) / 2);
        rect.offset(0, StateBarUtil.getStatusBarHeight(this) * -1);
        if (Build.VERSION.SDK_INT >= 24) {
            viewBean = new ViewBean(this.mNowPackName, this.mNowActivityName, charSequence, accessibilityNodeInfo.getViewIdResourceName(), rect, charSequence2, str, accessibilityNodeInfo.getDrawingOrder(), i4, i5, z2, accessibilityNodeInfo.isClickable(), accessibilityNodeInfo.isLongClickable(), accessibilityNodeInfo.isCheckable(), accessibilityNodeInfo.isEditable(), accessibilityNodeInfo.isScrollable());
        } else {
            viewBean = new ViewBean(this.mNowPackName, this.mNowActivityName, charSequence, viewIdResourceName, rect, charSequence2, str, 0, i4, i5, z2, accessibilityNodeInfo.isClickable(), accessibilityNodeInfo.isLongClickable(), accessibilityNodeInfo.isCheckable(), accessibilityNodeInfo.isEditable(), accessibilityNodeInfo.isScrollable());
        }
        viewBean.setListVieChild(z);
        this.mViewBeanList.add(viewBean);
    }

    public void controlView(ViewBean viewBean) {
        AccessibilityNodeInfo findNodeByLimit = findNodeByLimit(viewBean);
        if (findNodeByLimit == null) {
            EventBus eventBus = EventBus.getDefault();
            eventBus.post(new TopTipBean("找不到控件：" + viewBean.getNote()));
            return;
        }
        Rect rect = new Rect();
        findNodeByLimit.getBoundsInScreen(rect);
        int i = rect.left;
        int i2 = rect.top;
        int width = i + (rect.width() / 2);
        int height = i2 + (rect.height() / 2);
        int i3 = viewBean.getNowActioType().ordinal();
        if (i3 == 1) {
            clickXY(width, height, 50);
        } else if (i3 == 2) {
            clickXY(width, height, 2000);
        } else if (i3 == 3) {
            Bundle bundle = new Bundle();
            bundle.putCharSequence(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, viewBean.getStringValue());
            findNodeByLimit.performAction(2097152, bundle);
        } else if (i3 != 4) {
            if (i3 == 5 && findNodeByLimit.isChecked()) {
                clickXY(width, height, 50);
            }
        } else if (!findNodeByLimit.isChecked()) {
            clickXY(width, height, 50);
        }
    }

    public boolean findHasViewID(ViewBean viewBean) {
        List<AccessibilityNodeInfo> findViewByID = findViewByID(viewBean.getViewID());
        if (findViewByID == null || findViewByID.size() == 0) {
            return false;
        }
        return true;
    }

    public boolean findViewText(ViewBean viewBean) {
        AccessibilityNodeInfo findNodeByLimit = findNodeByLimit(viewBean);
        if (findNodeByLimit == null) {
            EventBus.getDefault().post(new TopTipBean("找不到目标控件"));
            return false;
        }
        CharSequence text = findNodeByLimit.getText();
        if (text == null || !text.toString().equals(viewBean.getTextValue())) {
            return false;
        }
        return true;
    }

    public boolean findViewDes(ViewBean viewBean) {
        AccessibilityNodeInfo findNodeByLimit = findNodeByLimit(viewBean);
        if (findNodeByLimit == null) {
            EventBus.getDefault().post(new TopTipBean("找不到目标控件"));
            return false;
        }
        CharSequence contentDescription = findNodeByLimit.getContentDescription();
        if (contentDescription == null || !contentDescription.toString().equals(viewBean.getDesValue())) {
            return false;
        }
        return true;
    }

    public boolean findViewState(ViewBean viewBean) {
        AccessibilityNodeInfo findNodeByLimit = findNodeByLimit(viewBean);
        if (findNodeByLimit == null) {
            EventBus.getDefault().post(new TopTipBean("找不到目标控件"));
            return false;
        } else if (findNodeByLimit.isChecked() == viewBean.isCheckState()) {
            return true;
        } else {
            return false;
        }
    }

    public AccessibilityNodeInfo findNodeByLimit(ViewBean viewBean) {
        this.mNodeInfoChose = null;
        int i = viewBean.getViewLimitType().ordinal();
        if (i == 1) {
            List<AccessibilityNodeInfo> findViewByID = findViewByID(viewBean.getLimitValue());
            if (findViewByID != null && findViewByID.size() > 0) {
                for (AccessibilityNodeInfo accessibilityNodeInfo : findViewByID) {
                    if (accessibilityNodeInfo.isVisibleToUser()) {
                        this.mNodeInfoChose = accessibilityNodeInfo;
                    }
                }
            }
        } else if (i == 2) {
            recycleALlViewDes(viewBean.getLimitValue(), getRootInActiveWindow());
        } else if (i == 3) {
            recycleALlViewText(viewBean.getLimitValue(), getRootInActiveWindow());
        } else if (i == 4) {
            recycleALlViewLocation(viewBean.getLimitValue(), getRootInActiveWindow());
        }
        return this.mNodeInfoChose;
    }

    public void recycleALlViewDes(String str, AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() == 0) {
                    CharSequence contentDescription = accessibilityNodeInfo.getContentDescription();
                    if (contentDescription != null && contentDescription.toString().equals(str)) {
                        this.mNodeInfoChose = accessibilityNodeInfo;
                        return;
                    }
                    return;
                }
                CharSequence contentDescription2 = accessibilityNodeInfo.getContentDescription();
                if (contentDescription2 != null && contentDescription2.toString().equals(str)) {
                    this.mNodeInfoChose = accessibilityNodeInfo;
                }
                for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                    try {
                        recycleALlViewDes(str, accessibilityNodeInfo.getChild(i));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void recycleALlViewText(String str, AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() == 0) {
                    CharSequence text = accessibilityNodeInfo.getText();
                    if (text != null && text.toString().equals(str)) {
                        this.mNodeInfoChose = accessibilityNodeInfo;
                        return;
                    }
                    return;
                }
                CharSequence contentDescription = accessibilityNodeInfo.getContentDescription();
                if (contentDescription != null && contentDescription.toString().equals(str)) {
                    this.mNodeInfoChose = accessibilityNodeInfo;
                }
                for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                    try {
                        recycleALlViewText(str, accessibilityNodeInfo.getChild(i));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void recycleALlViewLocation(String str, AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo != null) {
            try {
                if (accessibilityNodeInfo.getChildCount() == 0) {
                    Rect rect = new Rect();
                    accessibilityNodeInfo.getBoundsInScreen(rect);
                    rect.offset(0, StateBarUtil.getStatusBarHeight(this) * -1);
                    if (str.equals(rect.toString())) {
                        this.mNodeInfoChose = accessibilityNodeInfo;
                        return;
                    }
                    return;
                }
                Rect rect2 = new Rect();
                accessibilityNodeInfo.getBoundsInScreen(rect2);
                rect2.offset(0, StateBarUtil.getStatusBarHeight(this) * -1);
                if (str.equals(rect2.toString())) {
                    this.mNodeInfoChose = accessibilityNodeInfo;
                }
                for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
                    try {
                        recycleALlViewLocation(str, accessibilityNodeInfo.getChild(i));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public List<AccessibilityNodeInfo> findViewByID(String str) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow == null) {
            return null;
        }
        return rootInActiveWindow.findAccessibilityNodeInfosByViewId(str);
    }

    public String findLimitText(AccessibilityNodeInfo accessibilityNodeInfo, ViewBean viewBean) {
        CharSequence text;
        this.mNodeInfoChose = null;
        int i = viewBean.getViewLimitType().ordinal();
        if (i == 1) {
            List<AccessibilityNodeInfo> findItemViewByID = findItemViewByID(viewBean.getLimitValue(), accessibilityNodeInfo);
            if (findItemViewByID != null && findItemViewByID.size() > 0) {
                for (AccessibilityNodeInfo accessibilityNodeInfo2 : findItemViewByID) {
                    if (accessibilityNodeInfo2.isVisibleToUser()) {
                        this.mNodeInfoChose = accessibilityNodeInfo2;
                    }
                }
            }
        } else if (i == 2) {
            recycleALlViewDes(viewBean.getLimitValue(), accessibilityNodeInfo);
        } else if (i == 3) {
            recycleALlViewText(viewBean.getLimitValue(), accessibilityNodeInfo);
        } else if (i == 4) {
            recycleALlViewLocation(viewBean.getLimitValue(), accessibilityNodeInfo);
        }
        AccessibilityNodeInfo accessibilityNodeInfo3 = this.mNodeInfoChose;
        if (accessibilityNodeInfo3 == null || (text = accessibilityNodeInfo3.getText()) == null) {
            return "";
        }
        return text.toString();
    }

    public AccessibilityNodeInfo findLimitListViewNode(AccessibilityNodeInfo accessibilityNodeInfo, ViewBean viewBean) {
        this.mNodeInfoChose = null;
        int i = viewBean.getViewLimitType().ordinal();
        if (i == 1) {
            List<AccessibilityNodeInfo> findItemViewByID = findItemViewByID(viewBean.getLimitValue(), accessibilityNodeInfo);
            if (findItemViewByID != null && findItemViewByID.size() > 0) {
                for (AccessibilityNodeInfo accessibilityNodeInfo2 : findItemViewByID) {
                    if (accessibilityNodeInfo2.isVisibleToUser()) {
                        this.mNodeInfoChose = accessibilityNodeInfo2;
                    }
                }
            }
        } else if (i == 2) {
            recycleALlViewDes(viewBean.getLimitValue(), accessibilityNodeInfo);
        } else if (i == 3) {
            recycleALlViewText(viewBean.getLimitValue(), accessibilityNodeInfo);
        } else if (i == 4) {
            recycleALlViewLocation(viewBean.getLimitValue(), accessibilityNodeInfo);
        }
        return this.mNodeInfoChose;
    }

    public List<AccessibilityNodeInfo> findItemViewByID(String str, AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo == null) {
            return null;
        }
        return accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(str);
    }

    public String findPackName() {
        return this.mNowPackName;
    }

    public String findActivityName() {
        return this.mNowActivityName;
    }

    public void clickViewID(String str) {
        List<AccessibilityNodeInfo> findViewByID = findViewByID(str);
        if (findViewByID != null && findViewByID.size() > 0) {
            findViewByID.get(0);
            for (AccessibilityNodeInfo accessibilityNodeInfo : findViewByID) {
                if (accessibilityNodeInfo.isVisibleToUser()) {
                    clickNode(accessibilityNodeInfo);
                }
            }
        }
    }

    public void clickViewIDByPosition(String str, int i) {
        List<AccessibilityNodeInfo> findViewByID = findViewByID(str);
        if (findViewByID != null && findViewByID.size() > 0) {
            int i2 = i - 1;
            if (i2 < 0) {
                i2 = 0;
            }
            if (findViewByID.size() > i) {
                clickNode(findViewByID.get(i2));
            } else {
                clickNode(findViewByID.get(0));
            }
        }
    }

    private void clickNode(AccessibilityNodeInfo accessibilityNodeInfo) {
        if (accessibilityNodeInfo.isClickable()) {
            accessibilityNodeInfo.performAction(16);
            return;
        }
        Rect rect = new Rect();
        accessibilityNodeInfo.getBoundsInScreen(rect);
        int i = rect.left;
        int i2 = rect.right;
        int i3 = rect.top;
        int i4 = rect.bottom;
        clickXY(i + (rect.width() / 2), i3 + (rect.height() / 2), 50);
    }

    public List<PointBean> findViewByIDAll(String str) {
        this.mAllPointList = new ArrayList();
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow == null) {
            return null;
        }
        for (AccessibilityNodeInfo accessibilityNodeInfo : rootInActiveWindow.findAccessibilityNodeInfosByViewId(str)) {
            Rect rect = new Rect();
            accessibilityNodeInfo.getBoundsInScreen(rect);
            int i = rect.left;
            int i2 = rect.right;
            int i3 = rect.top;
            this.mAllPointList.add(new PointBean(i + ((i2 - i) / 2), i3 + ((rect.bottom - i3) / 2)));
        }
        return this.mAllPointList;
    }

    public boolean findHasViewIDByString(String str) {
        List<AccessibilityNodeInfo> findViewByID = findViewByID(str);
        if (findViewByID == null || findViewByID.size() == 0) {
            return false;
        }
        return true;
    }
}
